'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.session.token = '来了老弟';
    const id = ctx.get_params('id');
    if (id) {
      const user = await ctx.service.user.getById(id);
      ctx.body = user || '查无此人';
    } else {
      const users = await ctx.service.user.getAll();
      ctx.body = users;
    }
  }

  async add() {
    const { ctx } = this;
    const { name, age } = ctx.get_params();
    const user = await ctx.service.user.add(name, age);
    ctx.status = 201;
    console.log(user);
    ctx.body = user;
  }

  async update() {
    const { ctx } = this;
    const { id, name, age } = ctx.get_params();
    const newUser = await ctx.service.user.update(id, name, age);
    ctx.body = newUser;
  }

  async delete() {
    const { ctx } = this;
    const id = ctx.get_params('id');
    const res = await ctx.service.user.delById(id);
    ctx.body = res;
  }
  
}

module.exports = HomeController;
